﻿using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using System.Web;
using System.Xml;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;

using Axis.BusinessObject.Core;
using Axis.BusinessObject.Response;
using Axis.Dao.Core;
using Axis.Web.Administrator.Global;
using System.IO;
using Axis.Web.Views.Global;
using Axis.Dao.Research;
using Axis.BusinessObject.Research;

namespace Axis.Web.Views.Accounts
{
    public class AccountUI 
    {
        CMemberList member = new CMemberList();
        public AccountUI() { }
        public AccountUI(CMemberList member2) {
            member = member2;
        }
        protected string GetContentRegisterTemplate(string pUserID, string pEmail, string pPassword, string pVerifyCode)
        {
            try
            {
                string ret = string.Empty;
                StreamReader streamReader = File.OpenText(HttpContext.Current.Server.MapPath("~/Views/template/content_verify.txt"));
                ret = streamReader.ReadLine();
                while (streamReader.ReadLine() != null)
                {
                    ret += streamReader.ReadLine();
                }
                streamReader.Close();
                string domain = ConfigurationManager.AppSettings["Domain"];
                string contentMailVerifyCode = ConfigurationManager.AppSettings["ContentMailVerify"];
                string VERIFY_LINK = string.Format("{0}/Views/Accounts/Verify.aspx?ID={1}&VerifyCode={2}", domain, pUserID, pVerifyCode);
                ret = ret.Replace("[USER_NAME]", pEmail);
                ret = ret.Replace("[USER_PASSWORD]", pPassword);
                ret = ret.Replace("[VERIFY_LINK]", VERIFY_LINK);
                ret = ret.Replace("[VERIFY_MANUAL]", VERIFY_LINK);
                return ret;
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        public string MemberRegister(string pEmail, string pFirstName, string pLastName, string pPassword, string pDateOfBirth, string pGender, string pCaptcha,ref string captcha)
        {

            CApplicationMessage result = new CApplicationMessage();
            string email = pEmail.Trim();
           
            bool captchaValidate = CSecurity.ValidateMD5HashData(pCaptcha, captcha);
            if (captchaValidate == false)
            {
                captcha = "";
                result.Code = "CAPTCHA_INVALID";
                result.IsSuccessfull = false;
                result.Description = "Mã xác nhận không đúng.";
                return new JavaScriptSerializer().Serialize(result);
            }
            if (!EmailValidator(email))
            {
                result.Code = "EMAIL_INVALID";
                result.IsSuccessfull = false;
                result.Description = "Địa chỉ mail không hợp lệ.";
                return new JavaScriptSerializer().Serialize(result);
            }
            string password = CSecurity.GetMD5HashData(pPassword.Trim());
            if (password.Length < 6)
            {
                result.Code = "PASSWORD_INVALID";
                result.IsSuccessfull = false;
                result.Description = "Mật khẩu ít nhất 6 ký tự.";
                return new JavaScriptSerializer().Serialize(result);
            }
            string firstName = pFirstName.Trim();
            string lastName = pLastName.Trim();

            XmlDocument doc = new XmlDocument();
            XmlElement root = doc.CreateElement("InputValue");
            doc.AppendChild(root);
            root.SetAttribute("Action", "INSERT");
            root.SetAttribute("Email", email);
            root.SetAttribute("Password", password);
            root.SetAttribute("FirstName", firstName);
            root.SetAttribute("LastName", lastName);
            root.SetAttribute("DateOfBirth", pDateOfBirth);
            root.SetAttribute("Gender", pGender);
            root.SetAttribute("Avatar", "/Images/no-avatar.png");

            string inputValue = root.OuterXml;
            CCoreDao core = new CCoreDao();
            CApplicationMessage cApplicationMessage = core.ActionMemberList(inputValue);

            if (cApplicationMessage != null)
            {
                if (cApplicationMessage.IsSuccessfull)
                {
                    string id = cApplicationMessage.Result.ToString().Split('|')[0];
                    string verifyCode = cApplicationMessage.Result.ToString().Split('|')[1];

                    string mailContent = GetContentRegisterTemplate(id, pEmail, pPassword, verifyCode);
                    new CEmail().SendMail(email, "[6sao.vn] Thông tin kích hoạt tài khoản.", mailContent);
                }
            }
            return new JavaScriptSerializer().Serialize(cApplicationMessage);
        }

        public string Login(string pEmail, string pPassword, string pIsRemember, out  CMemberList member)
        {
            CCoreDao core = new CCoreDao();
            member = new CMemberList();
            string email = pEmail.Trim();
            string password = CSecurity.GetMD5HashData(pPassword.Trim());
            XmlDocument doc = new XmlDocument();
            XmlElement root = doc.CreateElement("InputValue");
            doc.AppendChild(root);
            root.SetAttribute("Email", email);
            root.SetAttribute("Password", password);
            string inputValue = root.OuterXml;
            CMemberLoginResponse response = core.MemberLogin(inputValue);
            StringBuilder ret = new StringBuilder();
            ret.Append("({");
            if (response.IsSuccessfull)
            {
             
                member = response.Member;
            //    CSecurity.IS_REMEMBER = pIsRemember == "true" ? true : false;
               /*  if (!string.IsNullOrEmpty(member.SecrectToken))
                {
                    CSecurity.MEMBER_SECRECT_TOKEN = member.SecrectToken;
                }                
               CSecurity.MEMBER_ID = member.ID;
                CSecurity.MEMBER_EMAIL = member.Email;
                CSecurity.MEMBER_FIRSTNAME = member.FirstName;
                CSecurity.MEMBER_LASTNAME = member.LastName;
                CSecurity.MEMBER_AVATAR = member.Avatar;              
                CSecurity.IS_MEMBER = true;
               */ 
                ret.AppendFormat("ID:'{0}',", member.ID);
                ret.AppendFormat("Avatar:'{0}',", member.Avatar);
                ret.AppendFormat("Email:'{0}',", member.Email);
                ret.AppendFormat("FirstName:'{0}',", member.FirstName);
                ret.AppendFormat("LastName:'{0}',", member.LastName);

            }
            ret.AppendFormat("IsSuccessfull:{0},", response.IsSuccessfull ? "true" : "false");
            ret.AppendFormat("Description:'{0}'", response.Description.Replace("'", "\""));
            ret.Append("})");
            return new JavaScriptSerializer().Serialize(response);
        }

        public string Logout(HttpContext current)
        {
            HttpContext.Current.Session.Abandon();
            HttpContext.Current.Session.Clear();
            foreach (string key in current.Request.Cookies.AllKeys)
            {
                HttpCookie cookie = new HttpCookie(key);
                cookie.Expires = DateTime.UtcNow.AddDays(-70);
                current.Response.Cookies.Add(cookie);
            }
            HttpContext.Current.Session["MEMBERINFO"] = null;
            current.Session.Abandon();
            current.Session.Clear();
            current.Response.Cookies.Clear();
            return "true";
        }

        
        public string CheckSession() {
            //if (Session["MEMBERINFO"] != null)
            //{
            //    CMemberList member = (CMemberList)Session["MEMBERINFO"];
            //    return ":"+  new JavaScriptSerializer().Serialize(member);
            //}
            return "no session";
        }

        public string CheckLogin(CMemberList member2)
        {
            CApplicationMessage message = new CApplicationMessage();
            var IsAuthenticated = member2.ID != 0;             
            if (IsAuthenticated)
            {
                message.Result = "Logged";
            }
           
            return new JavaScriptSerializer().Serialize(message);

        }

        public string CheckEmail(string pEmail)
        {
            string inputValue = string.Format("<InputValue Action='CHECK' Email='{0}' />", pEmail.Trim());
            /* Action */
            CCoreDao core = new CCoreDao();
            CApplicationMessage message = core.ActionMemberList(inputValue);
            string output = new JavaScriptSerializer().Serialize(message);
            return output;
        }

        public IList<CMemberList> GetMember(string inputValue)
        {          
            IList<CMemberList> list = new CCoreDao().GetMemberList(inputValue);
            return list;
            //return new JavaScriptSerializer().Serialize(list);
        }
        public string ForgotPassword(string pEmail, string pCaptcha, ref string pSessionCaptcha)
        {
            CApplicationMessage result = new CApplicationMessage();
            string captcha = pSessionCaptcha;
            pSessionCaptcha = "";         
            bool captchaValidate = CSecurity.ValidateMD5HashData(pCaptcha, captcha);
            if (captchaValidate == false)
            {                
                result.Code = "CAPTCHA_INVALID";
                result.IsSuccessfull = false;
                result.Description = "Mã xác nhận không đúng.";
                return new JavaScriptSerializer().Serialize(result);
            }

            string inputValue = string.Format("<InputValue Action='RESETPASSWORD' Email='{0}' />", pEmail);
            CApplicationMessage cApplicationMessage = new CCoreDao().ActionMemberList(inputValue);

            if (cApplicationMessage != null)
            {
                if (cApplicationMessage.IsSuccessfull)
                {
                    string verifyCode = cApplicationMessage.Result.ToString();
                    string mailContent = GetContentForgotPasswordTemplate(pEmail, verifyCode);
                    new CEmail().SendMail(pEmail, "[6sao.vn] Yêu cầu lấy lại mật khẩu.", mailContent);
                }
            }
            return new JavaScriptSerializer().Serialize(cApplicationMessage);
        }

        protected string GetContentForgotPasswordTemplate(string pEmail, string pVerifyCode)
        {
            try
            {
                string ret = string.Empty;
                StreamReader streamReader = File.OpenText(HttpContext.Current.Server.MapPath("~/Views/template/ForgotPassword.html"));
                ret = streamReader.ReadLine();
                while (streamReader.ReadLine() != null)
                {
                    ret += streamReader.ReadLine();
                }
                streamReader.Close();
                string domain = ConfigurationManager.AppSettings["Domain"];
                string contentMailVerifyCode = ConfigurationManager.AppSettings["ContentMailVerify"];
                string VERIFY_LINK = string.Format("{0}/Views/Accounts/Verify.aspx?Email={1}&VerifyCode={2}", domain, pEmail, pVerifyCode);
                ret = ret.Replace("[VERIFY_LINK]", VERIFY_LINK);
                ret = ret.Replace("[VERIFY_MANUAL]", VERIFY_LINK);
                return ret;
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        public string UpdateMember(string inputValue, CMemberList memberImput, out CMemberList updateMember)
        {
            CApplicationMessage message = new CCoreDao().ActionMemberList(inputValue);
            var IsAuthenticated =  memberImput.ID != 0;
            updateMember = memberImput;
            if (IsAuthenticated)

            if (message.IsSuccessfull)
            {
                IList<CMemberList> list = GetMember(string.Format( "<InputValue ID=\"{0}\" UserType=\"0\" UserID=\"{0}\"/>",member.ID));
                if (list != null && list.Count > 0)
                {
                    CMemberList member2 = list[0];
                    memberImput.FirstName = member2.FirstName;
                    memberImput.LastName = member2.LastName;
                    memberImput.Avatar = member2.Avatar;
                    updateMember = member2;
                }
            }
            return new JavaScriptSerializer().Serialize(message);
        }


        public string ActionMemberGift(string inputValue, CMemberList member)
        {
            CApplicationMessage message = new CResearchDao().ActionMemberGift(inputValue);

           
            
            if (message.IsSuccessfull)
            {
                IList<CMemberList> list = GetMember("<InputValue />");
                if (list != null && list.Count > 0)
                {
                    CMemberList member2 = list[0];
                    member.FirstName = member.FirstName;
                    member.LastName = member.LastName;
                    member.Avatar = member.Avatar;
                }
            }
            return new JavaScriptSerializer().Serialize(message);
        }

        protected bool EmailValidator(string email)
        {
            string pattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";

            Match match = Regex.Match(email, pattern, RegexOptions.IgnoreCase);

            if (match.Success)
                return true;
            else
                return false;
        }

        public string GetMemberGift()
        {
            StringBuilder Result = new StringBuilder();
            string Pattem = " <div class='Mark2GiftDialog_Gift' onclick='ChangeMarkToGift({3})'>" +
                    "<img class='Mark2GiftDialog_Gift_Image' src='{0}'>" +
                    "<span class='Mark2GiftDialog_Gift_Name'>{1}</span>" +
                    "<div class='Mark2GiftDialog_Gift_Mark'>" +
                        "<span class='Mark2GiftDialog_Gift_Mark_Value'>{2}</span>" +
                    "</div>" +
                "</div>";
            IList<CGift> list = new CResearchDao().GetGift("<InputValue UserID=\"1\" Context=\"ConvertMarkToGift\"  />");
            foreach (CGift item in list)
            {
                Result.AppendFormat(Pattem, item.Image, item.Name, item.Mark, item.ID);
            }
            return Result.ToString();
        }
    }
}